package etcd

import (
	"common/logs"
	"encoding/json"
	"fmt"
	"strings"
)

type Server struct {
	Name    string `json:"name"`
	Weight  int    `json:"weight"`
	Addr    string `json:"addr"`
	Version string `json:"version"`
	Ttl     int64  `json:"ttl"`
}

func NewServer() *Server {
	return &Server{}
}

func (s *Server) BindServerKey() string {
	if len(s.Version) == 0 {
		return fmt.Sprintf("/%s/%s", s.Name, s.Addr)
	}
	return fmt.Sprintf("/%s/%s/%s", s.Name, s.Version, s.Addr)
}

func ParseValue(value []byte) (Server, error) {
	var server Server
	if err := json.Unmarshal(value, &server); err != nil {
		logs.Info("value 解析失败")
	}
	return server, nil
}

/*
*
解析key
api/127.0.0.1:8080
api/v1/127.0.0.1:8080
*/
func ParseKey(key string) (Server, error) {
	var server Server
	i := len(key)
	str := strings.Split(key, "/")
	if i == 2 {
		return Server{
			Name: str[0],
			Addr: str[1],
		}, nil
	}
	if i == 3 {
		return Server{
			Name:    str[0],
			Addr:    str[2],
			Version: str[1],
		}, nil
	}
	return server, nil
}
